package com.example.demo.config.quartz;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class SchedulerConfig {
	
	@Autowired
	private SpringJobFactory springJobFactory;
	
	@Bean(name="SchedulerFactoryBean")
	public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		factory.setAutoStartup(true);
		factory.setStartupDelay(5);//延时5秒启动
		factory.setQuartzProperties(quartzProperties());
		factory.setJobFactory(springJobFactory);
		return factory;
	}
	
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
//        propertiesFactoryBean.setLocation(new ClassPathResource("/myQuartz.properties"));
        propertiesFactoryBean.setLocation(new FileSystemResource("myQuartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
    
    /**
     * 
     * @方法名 SchedulerConfig.java
     * @创建者 xzw
     * @创建日期 2020年11月22日
     * @返回类型 QuartzInitializerListener
     * @功能描述 quartz初始化监听器
     *
     */
    @Bean
    public QuartzInitializerListener executerListener() {
    	return new QuartzInitializerListener();
    }
    
    /**
     * 
     * @方法名 SchedulerConfig.java
     * @创建者 xzw
     * @创建日期 2020年11月22日
     * @返回类型 Scheduler
     * @功能描述 通过schedulerFactoryBean获取bean的实例
     *
     */
    @Bean(name="scheduler")
    public Scheduler scheduler() throws IOException {
    	return schedulerFactoryBean().getScheduler();
    }
}
